package com.matrix.rabbitmqtest.publishandconfirm;

import com.matrix.rabbitmqtest.util.AppKeys;
import com.matrix.rabbitmqtest.util.RabbitMQUtil;
import com.matrix.rabbitmqtest.util.RunningTimer;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.stream.IntStream;

/**
 * 批量发布确认
 */
public class BatchConfirmProducer {

    public static final int MSG_COUNT = 1000;

    public static void main(String[] args) throws IOException {
        // 获取一个信道
        Channel channel = RabbitMQUtil.getChannel();
        // 开启发布确认
        channel.confirmSelect();
        // 声明队列
        channel.queueDeclare(AppKeys.QUEUE_NAME, true, false, true, null);
        // 发送100条消息
        RunningTimer timer = new RunningTimer();
        IntStream.range(0, MSG_COUNT).forEach(i -> {
            try {
                channel.basicPublish("", AppKeys.QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, ("Hello RabbitMQ" + i).getBytes(StandardCharsets.UTF_8));
                // 每第99个消息确认一次,如果之前有消息确认失败,就会消息丢失, 不推荐使用
                if (i % 99 == 0) {
                    channel.waitForConfirms();
                    System.out.println("发布成功");
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        System.out.println("发布" + MSG_COUNT + "条消息, 耗时:" + timer.end() + "ms"); // 发布1000条消息, 耗时:296ms
    }
}
